<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/8/17
 * Time: 15:04
 */
namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;

class Test extends Controller{

	public function importArea(){
		set_time_limit(0);
		if(!$areas = Cache::get('areas')) {
			$filePath = 'area.xls';
			$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
			$objPHPExcel = \PHPExcel_IOFactory::load($filePath);
			$sheet = $objPHPExcel->getSheet(0);
			$highestRow = $sheet->getHighestRow(); // 取得总行数
			$highestColumn = $sheet->getHighestColumn(); // 取得总列数
//遍历行，遍历列，逐个读取数据：默认有标题，所以从第二行读起
			//循环读取excel文件,读取一条,插入一条
			$areas = [];
			for($j=2;$j<=$highestRow;$j++){
				$data = [];
				for($k='A';$k<=$highestColumn;$k++){
					$str = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();//读取单元格
					$data[] = $str;
				}
				
				if(!isset($areas[$data[1]])){
					$areas[$data[1]] = [
						'name' => $data[0],
						'citys' => []
					];
				}
				
				if(!isset($areas[$data[1]]['citys'][$data[3]])){
					$areas[$data[1]]['citys'][$data[3]] = [
						'name' => $data[2],
						'areas' => [$data[4]]
					];
				} else {
					$areas[$data[1]]['citys'][$data[3]]['areas'][] = $data[4];
				}
			}
		}
		
		
//		dump($areas);
		$i = 0;
		foreach($areas as $provice) {
			$proviceId = Db::name('areas')->insertGetId([
				'name' => $provice['name']
			]);
			$i ++;
			
			if($provice['citys']) {
				foreach($provice['citys'] as $city) {
					$cityId = Db::name('areas')->insertGetId([
						'pid' => $proviceId,
						'name' => $city['name']
					]);
					$i ++;
					
					if($city['areas']) {
						foreach($city['areas'] as $area) {
							Db::name('areas')->insertGetId([
								'pid' => $cityId,
								'name' => $area
							]);
							$i ++;
						}
					}
				}
			}
		}
		echo $i;
		
	}
	
	public function createAreaJson(){
		header('Content-type:text/html; charset=utf8');
		$provinces = Db::name('areas')->where(['pid'=>0])->field('id as value,name as text')->select();
		foreach($provinces as $pk => $province){
			$citys = Db::name('areas')->where(['pid'=>$province['value']])->field('id as value,name as text')->select();
			foreach ($citys as $k => $city) {
				$citys[$k]['children'] = Db::name('areas')->where(['pid'=>$city['value']])->field('id as value,name as text')->select();
				
			}
			$provinces[$pk]['children'] =$citys;
		};
		echo json_encode($provinces);
		die;
	}
}
